import $service from '../service'

class ConsultationWebsocket {
  constructor({ heartCheck, isReconnection }) {
    this.init = false;
    this.isConnect = false;
    this.netWork = true;
    this.isClosed = false;
    this.timeout = 3000;
    this.timeoutObj = null;
    this.connectNum = 0;
    this.heartCheck = heartCheck;
    this.isReconnection = isReconnection;
    this.consultationMsgCallBack = null;
    this.configuration = null
    // 使用会诊专用的 WebSocket 地址
    this.wsUrl = $service.consultationWsUrl;
    this.socketTask = null;
    // 是否呗邀请
    this.isInvited = false;

    wx.onNetworkStatusChange((res) => {
      this.netWork = res.isConnected;
      if (!this.netWork) {
        this.isConnect = false;
        if (this.isReconnection) {
          this.reConnect();
        }
      }
    });
  }

  // 初始化会诊WebSocket连接
  initConsultationSocket(options = {}) {
    if (this.isConnect) {
      console.log("会诊WebSocket已连接");
      return;
    }

    wx.getNetworkType({
      success: (res) => {
        if (res.networkType !== 'none') {
          this.connectSocket(options);
        } else {
          console.log('网络已断开');
          this.netWork = false;
        }
      }
    });
  }

  connectSocket(options = {}) {
    this.socketTask = wx.connectSocket({
      url: options.url || this.wsUrl,
      success: (res) => {
        console.log('会诊WebSocket连接创建成功');
        options.success?.(res);
      },
      fail: (err) => {
        console.error('会诊WebSocket连接创建失败', err);
        options.fail?.(err);
      }
    });

    this.initSocketListener();
  }

  initSocketListener() {
    if (!this.socketTask) return;

    this.socketTask.onOpen(() => {
      console.log('会诊WebSocket连接已打开');
      this.isConnect = true;
      this.init = true;

      // 发送会诊登录信息
      const loginData = JSON.stringify({
        token: wx.getStorageSync('miniToken'),
        packageType: 1
      });

      this.socketTask.send({
        data: loginData,
        success: () => {
          console.log('会诊登录信息发送成功');
          if (this.heartCheck) {
            this.reset().start();
          }
        }
      });
    });

    this.socketTask.onClose((res) => {
      console.log('会诊WebSocket连接已关闭:', res);
      this.isConnect = false;
      if (this.heartCheck) {
        this.reset();
      }
      if (!this.isClosed && this.isReconnection) {
        this.reConnect();
      }
    });

    this.socketTask.onError((err) => {
      console.error('会诊WebSocket错误:', err);
      this.isConnect = false;
      if (!this.isClosed && this.isReconnection) {
        this.reConnect();
      }
    });


    this.socketTask.onMessage(msg => {
      if (typeof msg.data === 'string' && msg.data.indexOf('{') === 0) {
        let res = JSON.parse(msg.data);
        console.log(res, '会诊消息数据');
        // 处理会诊特定消息类型
        switch (res.code) {
          case 1:
            this.configuration = {
              ...(res.configuration || {}),
            }
            break;
          case 3: // 会诊开始
            this.handleConsultationStart(res);
            break;
          case 6: // 医生离开
            this.handleConsultationEnd(res);
            break;
          default:
            // 其他消息类型
            break;
        }
        this.consultationMsgCallBack?.(res);
      }
    });
  }

  onConsultationMsg(callBack) {
    if (!this.socketTask) return;
    this.consultationMsgCallBack = callBack;
  }
  // 处理会诊开始
  handleConsultationStart(res) {
    this.configuration.room = res.roomId + ''
    wx.setStorageSync('cTencentConfig',  {
      room: res.roomId + '',
      ...(res.configuration || {})
    })
    // 判断当前页面地址
    const pages=getCurrentPages();
    //获取当前页面实例
    const currentPage=pages[pages.length-1];
    //获取当前页面路径
    const currentPagePath=currentPage.route;
    //判断页面类型
    console.log('currentPagePath',currentPagePath)
    if(currentPagePath==="pages/chat/consult_chat/consult_chat"){
      console.log("当前页面是会诊页");
      return
    }
    if (this.isInvited) {
      return;
    }
    this.isInvited = true
    wx.showModal({
      title: '温馨提示',
      showCancel: true,
      content: '您的服务医生邀请你进入专家会诊，房间号：' + res.roomId,
      success: (e) => {
        if (e.confirm) {
          // 邀请进入会诊
          wx.navigateTo({
            url: `/pages/chat/consult_chat/consult_chat?logId=${res.roomId}`
          });
        }
      }
    });
  }

  // 处理会诊结束
  handleConsultationEnd() {
    wx.showModal({
      title: '会诊结束',
      content: '本次会诊已结束',
      showCancel: false,
      success: () => {
        wx.navigateBack();
      }
    });
  }

  // 处理医生加入
  handleDoctorJoin(res) {
    // 处理医生加入逻辑
  }

  // 处理医生离开
  handleDoctorLeave(res) {
    wx.showModal({
      title: '温馨提示',
      showCancel: false,
      content: '会诊已结束',
      success: (e) => {
        if (e.confirm) {
          wx.navigateBack()
        }
      }
    });
  }

  // 发送会诊消息
  sendConsultationMsg(options) {
    if (!this.socketTask || !this.isConnect) {
      console.error('会诊WebSocket未连接');
      return;
    }

    this.socketTask.send({
      data: JSON.stringify(options.data),
      success: (res) => {
        options.success?.(res);
      },
      fail: (err) => {
        options.fail?.(err);
      }
    });
  }

  closeConsultationSocket() {
    if (this.socketTask) {
      this.socketTask.close({
        success: () => {
          console.log('会诊WebSocket已关闭');
        },
        fail: () => {
          console.log('会诊WebSocket关闭失败');
        }
      });
    }
    this.isClosed = true;
    this.isConnect = false;
    this.socketTask = null;
  }

  reset() {
    clearInterval(this.timeoutObj);
    return this;
  }

  start() {
    this.timeoutObj = setInterval(() => {
      if (this.socketTask && this.isConnect) {
        this.socketTask.send({
          data: 'ping',
          success: () => {
            // console.log("会诊心跳发送成功");
          },
          fail: (err) => {
            console.log(err);
            this.isConnect = false;
            if (!this.isClosed) {
              this.reConnect();
            }
            this.reset();
          }
        });
      }
    }, this.timeout);
  }

  reConnect() {
    console.log('正在重新连接会诊WebSocket, 当前重连次数:', this.connectNum);
    if (this.connectNum < 3) {
      setTimeout(() => this.initConsultationSocket(), 3000);
    } else if (this.connectNum < 10) {
      setTimeout(() => this.initConsultationSocket(), 10000);
    } else {
      setTimeout(() => this.initConsultationSocket(), 450000);
    }
    this.connectNum++;
  }
}

// 创建会诊WebSocket实例
const consultationWebsocket = new ConsultationWebsocket({
  heartCheck: true,
  isReconnection: true
});

export default consultationWebsocket;
